package com.umfwechat.util;

import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;


public class HttpHelper {
	private static final Logger logger = Logger.getLogger(HttpHelper.class);

	@SuppressWarnings("deprecation")
	public static Object getResObjPost(String urlstr,XStream stream,Object obj)throws Exception{
		InputStreamReader reader =null;
		HttpClient httpclient = null;
		PostMethod post = null;
		try{
			//创建httpclient
			httpclient = new HttpClient();
			//配置读超时时间
			httpclient.getHttpConnectionManager().getParams().setSoTimeout(60 * 1000);
			//配置连接超时时间
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(60 * 1000);
			logger.info("now to send! url is " + urlstr);
			post = new PostMethod(urlstr);

			post.addRequestHeader("Content-Type", "text/xml");
			post.addRequestHeader("Charset", "UTF-8");			
			
			post.setRequestBody(new ByteArrayInputStream(stream.toXML(obj).getBytes("UTF-8")));
			int statusCode = httpclient.executeMethod(post);
			if (statusCode == HttpStatus.SC_OK) {
				logger.info("接收响应ok！");
				logger.info(post.getResponseBodyAsStream().toString());
				reader = new InputStreamReader(post.getResponseBodyAsStream(), "UTF-8");
				logger.info("读入reader OK！");
				stream = new XStream(new DomDriver());
				obj =  stream.fromXML(reader);
				return obj;
			}else if (statusCode == HttpStatus.SC_GATEWAY_TIMEOUT) {
				logger.info("接收响应超时！");
				Map<String, String> resobj = new HashMap<String, String>();
				resobj.put("retCode", String.valueOf(statusCode));
				resobj.put("retMsg", "连接目标系统超时");
				return resobj;
			}else{
				logger.info("接收响应错误！");
				return null;
			}
		}catch(SocketTimeoutException se){
			logger.error(se);
			Map<String, String> resobj = new HashMap<String, String>();
			resobj.put("retCode", "9999");
			resobj.put("retMsg", "连接目标系统错误");
			return resobj;
		}catch(Exception tht){
			logger.error(tht);
			return null;
		}catch(Error er){
			logger.error(er);
			return null;			
		}finally{
			try{
				reader.close();
			}catch(Exception e){
				reader=null;
			}
			if(post != null){
				try{
					post.releaseConnection();
				}finally{
					post = null;
				}
			}
			if(httpclient != null){
				try {
					 httpclient.getHttpConnectionManager().closeIdleConnections(0);
				}finally{
					httpclient = null;
				}
			}
		}
	}
}
